package com.IntelligentCommunity.common.core.utils.file;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
/**
 * @author 美国五星上将麦克阿瑟
 */
public class Url2Base64 {

    public static String getBase64(String url) {
        String imageUrl = url;
        try {
            String base64String = downloadImageAndConvertToBase64(imageUrl);
            return base64String;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String downloadImageAndConvertToBase64(String imageUrl) throws IOException {
        URL url = new URL(imageUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        try (InputStream inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {

            int bytesRead;
            byte[] buffer = new byte[4096];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }

            byte[] imageData = byteArrayOutputStream.toByteArray();
            String base64String = Base64.getEncoder().encodeToString(imageData);
            return base64String;
        } finally {
            httpURLConnection.disconnect();
        }
    }
}
